package com.homework.ch10;

import java.util.Random;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/14
 * @Description:
 */
class SaleWindow implements Runnable{
    //共享的资源，票数50
    //tickers static
    private static int num=50;
    Random random=new Random();
    @Override
    public void run() {
        //上锁[   同步代码块,同步对象是静态的，锁：xx.class
        //买票 票数--
        //输出买了票还剩余多少
        //]
        //随机睡眠100-200
        while(true){
            synchronized (SaleWindow.class){
                //if(num>0) num--;
                if (num<=0){
                    break;
                }
                System.out.println(Thread.currentThread().getName()+"卖出票，剩余票数："+num);
                num--;
            }
            try {
                Thread.sleep(100+random.nextInt(101));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Test7 {
    public static void main(String[] args) {
        Thread t1=new Thread(new SaleWindow(),"窗口1");
        Thread t2=new Thread(new SaleWindow(),"窗口2");
        Thread t3=new Thread(new SaleWindow(),"窗口3");
        Thread t4=new Thread(new SaleWindow(),"窗口4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

